package com.ynding.cloud.common.util.bean;

import com.google.common.collect.Maps;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p> </p>
 *
 * @author ynding
 * @version 2021/5/27
 **/
public class ObjectUtil {

    /**
     * 获取单个对象的所有键值对
     *
     * @param t
     * @param <T>
     * @return
     */
    public static <T> Map<String, Object> getKeyAndValue(T t) {
        Map<String, Object> map = Maps.newHashMap();
        Class clazz = (Class) t.getClass();
        Field[] fields = clazz.getDeclaredFields();
        map = Arrays.stream(fields).collect(Collectors.toMap(Field::getName, field -> {
            Object resultObj = null;
            field.setAccessible(true);
            try {
                resultObj = field.get(t);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return Optional.ofNullable(resultObj).orElse(0);
        }, (k1, k2) -> k2));
        return map;
    }

    /**
     * 获取类中属性名列表
     * @param c  类
     * @param <T> 类
     * @return
     */
    public static <T> List<String> getAttributes(Class<T> c) {
        List<String> table = new ArrayList<>();
        Field[] propertyNames = c.getDeclaredFields();
        for (Field field : propertyNames) {
            table.add(field.getName());
        }
        return table;
    }
}
